package com.tarena.lbs.basic.service.impl;

import com.tarena.lbs.basic.dao.repository.TagRepository;
import com.tarena.lbs.basic.pojo.po.TagLibraryPO;
import com.tarena.lbs.basic.pojo.vo.TagLibraryVO;
import com.tarena.lbs.basic.pojo.vo.TagVO;
import com.tarena.lbs.basic.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagRepository tagRepository;

    @Override
    public Map<String, List<TagVO>> getTags(Integer type) {
        List<TagLibraryPO> allTags = tagRepository.getTags(type);
        Map<String, List<TagVO>> resultMap = new HashMap<>();
        List<TagLibraryPO> firstLevelTags = new ArrayList<>();
        for (TagLibraryPO tag : allTags) {
            if (tag.getTagParentId() == 0) {
                firstLevelTags.add(tag);
            }
        }
        for (TagLibraryPO firstLevelTag : firstLevelTags) {
            String firstLevelTagName = firstLevelTag.getTagName();
            resultMap.put(firstLevelTagName, new ArrayList<>());
        }
        for (TagLibraryPO tag : allTags) {
            if (tag.getTagParentId() != 0) {
                for (TagLibraryPO firstLevelTag : firstLevelTags) {
                    if (firstLevelTag.getId().equals(tag.getTagParentId())) {
                        String firstLevelTagName = firstLevelTag.getTagName();
                        TagVO tagVO = new TagVO();
                        BeanUtils.copyProperties(tag, tagVO);
                        tagVO.setTagCategoryName(firstLevelTagName);
                        TagLibraryVO ta = new TagLibraryVO();
                        BeanUtils.copyProperties(tag, ta);
                        tagVO.setTagLibraryBO(ta);
                        resultMap.get(firstLevelTagName).add(tagVO);
                        break;
                    }
                }
            }
        }
        return resultMap;
    }
}
